package cn.jietuo.juc.c_004_exception;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/4
 * @description: 程序在执行过程中，如果出现异常，默认情况锁会被释放
 */
public class T01 {

    private int count = 0;

    public synchronized void m() {
        System.out.println("m start");

        while (true) {
            count++;
            System.out.println(Thread.currentThread().getName() + ",count:" + count);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 5) {
                //此处抛出异常，锁将被释放，要想不被释放，可以在这里进行catch，然后让循环继续
                int i = count / 0;
                System.out.println(i);

//                try {
//                    int i = count / 0;
//                    System.out.println(i);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        }
    }

    public static void main(String[] args) {
        T01 t01 = new T01();
        new Thread(() -> {
            t01.m();
        }).start();

        new Thread(() -> {
            t01.m();
        }).start();
    }
}
